package com.autonavi.yunda.yunji.core.service;

import com.alibaba.ais.skyline.client.http.SkylineHttpClient;
import com.alibaba.ais.skyline.domain.search.QueryRequest;
import com.autonavi.yunda.yunji.core.config.ApplicationEnvConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author cizhong.wcs
 * @date 2022/7/19 17:29
 */
@Slf4j
@Component
public class SkylineIpServiceImpl implements IIpService {
    @Autowired
    private SkylineHttpClient skylineHttpClient;

    @Autowired
    private ApplicationEnvConfig applicationEnvConfig;

    private String localHostIp = null;

    @PostConstruct
    public void initLocalHostIp() throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();
        localHostIp = address.getHostAddress();
        log.info("host ip is {}", localHostIp);
    }

    @Override
    public List<String> fetchEngineIpList() {
        return fetchEngineIpListBySkyline();
    }

    @Override
    public String fetchLocalhostIp() {
        return localHostIp;
    }

    private List<String> fetchEngineIpListBySkyline() {
        return queryIpsFromSkyline("cloudmap-yunji-engine", "cloudmap-yunji-engine_testing_3358547_testhost");
    }

    public List<String> fetchJobExecutorIp() {
        return queryIpsFromSkyline("cloudmap-yunji-job-executor", "cloudmap-yunji-job-executor_testing_4530050_testhost");
    }

    public List<String> queryIpsFromSkyline(String appName, String daily_env_group_name) {
        QueryRequest request = new QueryRequest();
        request.setFrom("server");
        request.setSelect(" ip,app_group.name");
        request.setPage(1);
        request.setNum(1000);
        if (applicationEnvConfig.isPublish() || applicationEnvConfig.isPrepub()) {
            request.setCondition("app.name = '" + appName + "'");
            return skylineHttpClient.itemSearch().dump(request).getValue().getItemList()
                    .stream().filter(map -> {
                        String groupName = (String) map.get("app_group.name");
                        if (applicationEnvConfig.isPrepub()) {
                            return groupName.contains("prehost");
                        } else {
                            return !groupName.contains("prehost");
                        }
                    }).map(map -> (String) map.get("ip")).collect(Collectors.toList());
        } else {
            request.setCondition("app_group.name = '" + daily_env_group_name + "'");
            return skylineHttpClient.itemSearch().dump(request)
                    .getValue().getItemList()
                    .stream().map(map -> (String) map.get("ip"))
                    .collect(Collectors.toList());
        }
    }
}
